package com.enhe.gck.fg;

import com.enhe.gck.com.oracle.OracleController;
import com.enhe.gck.communal.PublicConstant;
import com.enhe.gck.communal.PublicMethod;
import com.enhe.gck.communal.PublicReturn;
import com.enhe.gck.item.OrderHWANE16677Item;
import com.enhe.gck.item.RechargeHWANE16698Item;
import com.enhe.gck.pojo.*;
import com.kuangkie.carbon.common.IntegrationMsg;
import com.kuangkie.carbon.fg.*;
import com.kuangkie.carbon.fg.ops.FGOpsComplexus;
import com.kuangkie.carbon.fg.ops.ProRecordOps;
import com.kuangkie.carbon.fg.ops.ProRecordOpsBuilder;
import com.kuangkie.carbon.panel.CarbonPanel;
import com.kuangkie.carbon.record.FGRecordBuilder;
import com.kuangkie.carbon.record.ProRecordBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import com.kuangkie.carbon.record.FGRecordComplexus;
import com.kuangkie.carbon.record.ProRecord;
import com.enhe.gck.CarbonBaseConstant; //模型Code
import com.enhe.gck.CarbonEnumKeyValue; //枚举字典信息
import com.enhe.gck.CarbonRelationType; //关系类型Code
import com.enhe.gck.item.BillingRecordsHWANE20727Item; // 模型属性Code

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Repository(value = "hwane20727366042330866425862")
@Slf4j
public class BillingRecordsHWANE20727BNB implements FirstRoundImproveFuncGroup,SecondRoundImproveFuncGroup, FuseCallBackFuncGroup {

	@Resource
	private RechargeHWANE16698BNB rechargeHWANE16698BNB;
	@Resource
	private ConfigHWANE16627BNB configHWANE16627BNB;
	@Override
	public void secondImprove(FuncGroupContext context, ProRecord proRecord, FGRecordComplexus recordComplexus,
			ImproveResultFactory improveResultFactory) {
		BillingRecords info=proRecord.getBean(BillingRecords.class);
		ProRecordOpsBuilder setData=improveResultFactory.getCurrentProRecordOpsBuilder();
		if(info.getIsDelete()==null||!info.getIsDelete()){
			if(proRecord.isNew()){
				OperationLogHWANE21797BNB.save(improveResultFactory,8,1,proRecord.getRecordCode());
				setData.putAttribute(BillingRecordsHWANE20727Item.基本属性组_状态,CarbonEnumKeyValue.收款状态_待收款_dsk);

				if(info.getUnit()==null||info.getUnit().compareTo(BigDecimal.ZERO)<1){
					PublicMethod.returnMessage(improveResultFactory, PublicReturn.Input_3);
					return ;
				}
			}

			if(String.valueOf(CarbonEnumKeyValue.收款状态_已收款_ysk).equals(info.getState())){
				log.info("创建实际{},比较时间{}",info.getCreateTime(),LocalDate.now().atStartOfDay());
				if(info.getCreateTime().isBefore(LocalDate.now().atStartOfDay())){
					PublicMethod.returnMessage(improveResultFactory,PublicReturn.BillingRecords_1);
					return;
				}

				if(info.getIsCombination()){
					if(VerifyCompliance(info.getMoneyM(),info.getMoneyF(),info.getWeight(),info.getUnit(),info.getExchange(),improveResultFactory)){
					}
				}
			}
		}else {
			if(String.valueOf(CarbonEnumKeyValue.收款状态_已收款_ysk).equals(info.getState())){
				PublicMethod.returnMessage(improveResultFactory,PublicReturn.BillingRecords_2);
				return;
			}else {
				if(!proRecord.isNew()){
					BillingRecords infoOld=PublicMethod.getInfo(CarbonBaseConstant.开单记录_kdjl,proRecord.getRecordCode(),BillingRecords.class,1);
					if(!(infoOld.getIsDelete()!=null&&infoOld.getIsDelete())){
						OperationLogHWANE21797BNB.save(improveResultFactory,8,3,proRecord.getRecordCode());
					}
				}
			}
		}
	}

	@Override
	public boolean afterFusition(FuncGroupContext funcGroupContext, FuseContext fuseContext, String s) {
		BillingRecords info=PublicMethod.getInfo(CarbonBaseConstant.开单记录_kdjl,s,BillingRecords.class,2);
		if(info.getIsDelete()==null||!info.getIsDelete()){
			if(String.valueOf(CarbonEnumKeyValue.收款状态_已收款_ysk).equals(info.getState())&&!info.getIsOk()){
				ProRecordBuilder aa=CarbonPanel.getProRecordBuilder(CarbonBaseConstant.开单记录_kdjl,s);
				saveReOrOrder(info,aa);
				IntegrationMsg msg1=aa.integrate();
				if(!msg1.success()){
					log.info("QAQ开单信息修改失败{}",msg1.getRefuseMsgContentStr());
				}
			}
		}

		return true;
	}

	private boolean saveReOrOrder(BillingRecords info, ProRecordBuilder ff){
		boolean flag=false;
		Recharge data=new Recharge();
		data.setType(String.valueOf(CarbonEnumKeyValue.充值记录_充值类型_普通_pt));
		List<String> rechargeList=new ArrayList<String>();

		Univalence univalence=new Univalence();
		univalence.setUnit(info.getUnit().doubleValue());
		univalence.setTaxRate(info.getTaxRate().doubleValue());
		univalence.setGoodsId(info.getGoods().getId());
		data.setUnivalence(univalence);
		data.setUnivalenceId(univalence.getId());
		data.setCustomerId(info.getCustomer()==null?null:info.getCustomer().getId());
		IntegrationMsg msg1=null;
		//添加组合支付判断
		if(!info.getIsCombination()){
			data.setBankId(info.getBank()==null?null:info.getBank().getId());
			data.setCurrency(info.getCurrency());
			if(String.valueOf(CarbonEnumKeyValue.币种_USD_).equals(info.getCurrency())){
				data.setMoneyCurrency(info.getMoney().doubleValue());
			}else {
				data.setMoneyCurrency(PublicMethod.multiplyBigDecimal(info.getWeight(),PublicMethod.multiplyBigDecimal(info.getUnit(),info.getExchange(),PublicConstant.leastCDF,null),PublicConstant.leastUSD,null).doubleValue());
			}
			msg1=CarbonPanel.getRecordIntegration(CarbonBaseConstant.充值记录_czjl).integrate(data);
		}else {
			data.setBankId(info.getBank()==null?null:info.getBank().getId());
			data.setCurrency(info.getCurrency());
			data.setMoneyCurrency(info.getMoneyM().doubleValue());

			IntegrationMsg msg11=CarbonPanel.getRecordIntegration(CarbonBaseConstant.充值记录_czjl).integrate(data);

			if(msg11.success()){
				rechargeList.add(msg11.getRecordCode());
				ff.addRelation(CarbonRelationType.RR_开单记录_充值记录_充值记录,msg11.getRecordCode());

				data.setBankId(info.getBank2()==null?null:info.getBank2().getId());
				data.setCurrency(info.getCurrency2());
				data.setMoneyCurrency(info.getMoneyF().doubleValue());

				msg1=CarbonPanel.getRecordIntegration(CarbonBaseConstant.充值记录_czjl).integrate(data);
			}else {
				log.info("QAQ组合付款充值记录添加失败{}",msg11.getRefuseMsgContentStr());
			}
		}

        if (msg1 != null && msg1.success()) {
			rechargeList.add(msg1.getRecordCode());
            ff.addRelation(CarbonRelationType.RR_开单记录_充值记录_充值记录, msg1.getRecordCode());
            Order order = new Order();
            if (String.valueOf(CarbonEnumKeyValue.订单记录_类型_袋装_dz).equals(info.getGoods().getType())) {
                order.setBags(info.getBags());
                order.setSingleWeight(Double.valueOf(configHWANE16627BNB.getConfigValueOneWeight()));
            } else {
                order.setWeight(info.getWeight().doubleValue());
            }
            order.setIsRetail(String.valueOf(CarbonEnumKeyValue.是否_是_s));
            order.setOrderSource(String.valueOf(CarbonEnumKeyValue.订单来源_PC_));
			order.setCollectType(String.valueOf(CarbonEnumKeyValue.订单信息_收货类型_自提_zt));
            order.setCustomerSId(info.getCustomer() == null ? null : info.getCustomer().getId());
            order.setCarId(info.getCar() == null ? null : info.getCar().getId());
            order.setDriverId(info.getDriver() == null ? null : info.getDriver().getId());
            order.setGoodsId(info.getGoods() == null ? null : info.getGoods().getId());
            IntegrationMsg msg2 = CarbonPanel.getRecordIntegration(CarbonBaseConstant.订单记录_ddjl).integrate(order);
            if (msg2.success()) {
                flag = true;
                ff.addRelation(CarbonRelationType.RR_开单记录_订单记录_订单记录, msg2.getRecordCode());
                ff.putAttribute(BillingRecordsHWANE20727Item.基本属性组_生成, true);
            } else {
                log.info("QAQ订单添加失败{}", msg2.getRefuseMsgContentStr());
				for (String x : rechargeList) {
					log.info("QAQ订单添加失败触发充值记录作废{}", x);
					ProRecordBuilder aaa=CarbonPanel.getProRecordBuilder(CarbonBaseConstant.充值记录_czjl,x);
					aaa.putAttribute(RechargeHWANE16698Item.基本属性组_作废,true);
					IntegrationMsg upMsg=aaa.integrate();
					if(!upMsg.success()){
						log.info("QAQ作废{}失败{}", x,upMsg.getRefuseMsgContentStr());
					}
				}
				log.info("QAQ开单记录状态修改{}", info.getRecordCode());
				ff.putAttribute(BillingRecordsHWANE20727Item.基本属性组_状态, CarbonEnumKeyValue.收款状态_待收款_dsk);
			}
        }
        return flag;
	}

	private boolean VerifyCompliance(BigDecimal moneyM,BigDecimal moneyF,BigDecimal weight,BigDecimal unit,BigDecimal rate,ImproveResultFactory improveResultFactory){
		boolean flag=false;
		BigDecimal moneyMF=PublicMethod.divideBigDecimal(moneyF,rate,PublicConstant.leastUSD, null);
		BigDecimal money=moneyMF.add(moneyM);
		BigDecimal weightOk=PublicMethod.divideBigDecimal(money,unit,PublicConstant.weightDecimals, RoundingMode.DOWN);
		if(weightOk.compareTo(weight)<0){
			log.info("重量验证失败计划拉运{}t,实际可拉运{}t",weight,weightOk);
			PublicMethod.returnMessage(improveResultFactory,PublicReturn.BillingRecords_3);
			flag=true;
		}
		return flag;
	}


	@Override
	public void preImprove(FuncGroupContext funcGroupContext, ProRecord proRecord, ProRecordOps proRecordOps, FGRecordComplexus fgRecordComplexus, FGOpsComplexus fgOpsComplexus, ImproveResultFactory improveResultFactory) {

	}

	@Override
	public void improve(FuncGroupContext funcGroupContext, ProRecord proRecord, FGRecordComplexus fgRecordComplexus, ImproveResultFactory improveResultFactory) {
		BillingRecords info=proRecord.getBean(BillingRecords.class);
		ProRecordOpsBuilder setData=improveResultFactory.getCurrentProRecordOpsBuilder();
		Goods goods=CarbonPanel.getRecordDiscover(CarbonBaseConstant.产品管理_cpgl).getRecordBean(proRecord.getGuestRecordCode(CarbonRelationType.RR_开单记录_产品_产品管理),Goods.class,1);
		if(String.valueOf(CarbonEnumKeyValue.订单记录_类型_袋装_dz).equals(goods.getType())){
			if(info.getBags()==null){
				PublicMethod.returnMessage(improveResultFactory,PublicReturn.ORDER_17);
				return;
			}
			log.info("QAQ袋装验证产品范围");
			if(String.valueOf(CarbonEnumKeyValue.订单记录_类型_袋装_dz).equals(goods.getType())){
				//防止数据修改
				if((goods.getMinimum()!=null&&PublicMethod.compareToBigDecimal(goods.getMinimum(),info.getBags())>0)||
						(goods.getMost()!=null&&PublicMethod.compareToBigDecimal(goods.getMost(),info.getBags())<0)
				){
					PublicMethod.returnMessage(improveResultFactory,PublicReturn.ORDER_13);
					return;
				}
			}
		}else {
			if(info.getWeight()==null){
				PublicMethod.returnMessage(improveResultFactory,PublicReturn.ORDER_16);
				return;
			}
			improveResultFactory.getCurrentProRecordOpsBuilder().putAttribute(BillingRecordsHWANE20727Item.基本属性组_下单数量_袋_,null);
			log.info("QAQ散装验证产品范围");
			if(!String.valueOf(CarbonEnumKeyValue.订单记录_类型_袋装_dz).equals(goods.getType())){
				//防止数据修改
				if(goods.getMinimum()!=null&&PublicMethod.compareToBigDecimal(goods.getMinimum(),info.getWeight())>0||
						goods.getMost()!=null&&PublicMethod.compareToBigDecimal(goods.getMost(),info.getWeight())<0){
					PublicMethod.returnMessage(improveResultFactory,PublicReturn.ORDER_13);
					return;
				}
			}
		}

		if(String.valueOf(CarbonEnumKeyValue.订单记录_类型_袋装_dz).equals(goods.getType())){
			String value =configHWANE16627BNB.getConfigValueOneWeight();
			info.setWeight(PublicMethod.multiplyBigDecimal(value,info.getBags(),PublicConstant.weightDecimals,null));
			setData.putAttribute(BillingRecordsHWANE20727Item.基本属性组_重量_t_,PublicMethod.multiplyBigDecimal(value,info.getBags(),PublicConstant.weightDecimals,null));
		}

		//处理
		BigDecimal exchange=rechargeHWANE16698BNB.getExchange();
		if(exchange==null){
			PublicMethod.returnMessage(improveResultFactory, PublicReturn.Recharge_1);
			return;
		}
		setData.putAttribute(BillingRecordsHWANE20727Item.基本属性组_计算汇率,exchange);

		info.setMoney(PublicMethod.multiplyBigDecimal(info.getWeight(),info.getUnit(),PublicConstant.leastUSD,RoundingMode.UP));
		setData.putAttribute(BillingRecordsHWANE20727Item.基本属性组_金额,info.getMoney());
		info.setMoneyG(PublicMethod.multiplyBigDecimal(info.getMoney(),exchange,PublicConstant.leastCDF,null));
		setData.putAttribute(BillingRecordsHWANE20727Item.基本属性组_刚果法郎金额,info.getMoneyG());
	}

	@Override
	public void postImprove(FuncGroupContext funcGroupContext, ProRecord proRecord, FGRecordComplexus fgRecordComplexus, ImproveResultFactory improveResultFactory) {

	}
}
